import React, { useEffect, useState } from 'react';
import { Button, message, Space, Spin, Tooltip } from 'antd';
import { connect } from 'umi';
import { useSetState } from 'ahooks';
import _ from 'lodash';
import QueueAnim from 'rc-queue-anim';
// @ts-ignore
import { OnHistory } from '#/utils/interactive';
import { CloseOutlined } from '#/utils/antdIcons.js';
import { export_json_to_excel, exportGroup } from '@/utils/fileExport.js';
import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';

import {
  deleteXinjiangContract,
  getContractTypeCodes,
  getStationLevelThree,
  getXinjiangContractList,
  postContractDel,
  postContractDetail,
  postContractEdit,
  postContractList,
  postCsontractPriceFluctuation,
  postMonthTotal,
  postOneDayTotal,
  postXJContractCreate,
  postXJContractEdit,
} from './service';
import {
  extractTree,
  getDealElementOptions,
  havePermissions,
  ToFixed,
  USER_TYPE_DIC,
  xinjiangExportDic,
} from './tool';
import {
  contractSourceOptions,
  pointerOptions,
  positionsCalculateOptions,
  timeSliceObjType,
  tradeDirectionOptions,
} from './dictionary';
import type {
  IDealElementOptions,
  IFromValue,
  IListType,
  IProps,
  ISearchFormData,
  ISearchValue,
} from './type';
import {
  IContractPermissions,
  IContractSourceType,
  IContractType,
  IDrawerType,
  IPickerType,
  IPointerType,
  IPositionsCalculateType,
  IRequireType,
  ITradeDirectionType,
} from './type';
import {
  Charts,
  ConfirmModal,
  Detail,
  Header,
  List,
  Pointer,
  SpecialDatePicker,
  XJDetail,
  XJList,
} from './components/index';
import styles from './index.less';
import moment from 'moment';
import { useTRState } from '#/utils/trHooks.jsx';

const ContractManagement = (props: IProps) => {
  const { buttonPermissions, menuCode } = props;
  const [isXinJiang, setIsXinJiang] = useState<boolean>(false);
  const [totalData, setTotalData] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(true);
  const [formValue, setFormValue] = useSetState<IFromValue>({});
  const [initFromValue, setInitFromValue] = useSetState<IFromValue>({});
  const [dataSource, setDataSource] = useState<IListType[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [isShow, setIsShow] = useState<boolean>(false); // 是否切换了数据列表
  const [monthData, setMonthData] = useState<any>(); // 全部合约电价数据-月份
  const [dateData, setDateData] = useState<any>(); // 全部合约电价数据-日期
  const [monthChartsData, setMonthChartsData] = useState<any>(); // 合约电价数据-月份
  const [dateChartsData, setDateChartsData] = useState<any>(); // 合约电价数据-日期
  const [isMonthError, setIsMonthError] = useState<boolean>(false); //查询Echarts数据是否报错-月份
  const [isDateError, setIsDateError] = useState<boolean>(false); //查询Echarts数据是否报错-日期
  const [monthChartsLoading, setMonthChartsLoading] = useState<boolean>(false); //查询Echarts数据是否加载中-月份
  const [dateChartsLoading, setDateChartsLoading] = useState<boolean>(false); //查询Echarts数据是否加载中-日期
  const [nowMonth, setNowMonth] = useState<string>(); // 合约量价信息-月份 当前选中的月份
  const [nowDate, setNowDate] = useState<string>(); // 合约量价信息-日期 当前选中的日期
  const [isLoading, setIsLoading] = useState<boolean>(true); // 合约管理列表是否加载中；
  const [isError, setIsError] = useState<boolean>(false); // 合约管理列表是否报错
  const [drawerType, setDrawerType] = useState<IDrawerType>(IDrawerType?.ADD); //当前显示抽屉的状态
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false); // 抽屉是否展示
  const [drawerLoading, setDrawerLoding] = useState<boolean>(false); // 抽屉取消按钮和确认按钮是否显示loading状态
  const [pointNum, setPointNum] = useState<IPointerType>(IPointerType.NINETY_SIX_POINT); // 时点
  const [nowChartRecord, setNowChartRecord] = useState<IListType | any>({}); // 当前Chart使用的列表数据数据
  const [nowRecord, setNowRecord] = useState<IListType | any>({}); // 当前Chart使用的列表数据数据
  const [overviewData, setOverviewData] = useState<IListType | any>({}); //合计行数据
  const [searchFormData, setSearchFormData] = useSetState<ISearchFormData>({
    dealElementOptions: [],
    dealElementModalOptions: [],
    originDealElementOptions: [],
    dealElementDataObj: {},
  });
  const [state, setState] = useTRState({
    contractTypeList: [],
    power: [],
    provinceId: '',
    stationOptions: [],
    stationList: [],
  });

  // 判断主合约和辅助合约
  const getDataSource = (data: { dataList: IListType[]; totalBody: any }, params: ISearchValue) => {
    const noRepeat: any = [];
    // //添加合计行
    // data?.dataList?.unshift({
    //   stationName: '合计',
    //   contractName: '合计',
    //   ...data?.totalBody,
    //   contractStartDate: params.beginDate,
    //   contractEndDate: params.endDate,
    // });
    setOverviewData(data?.totalBody);
    return data?.dataList
      ?.filter((item) => {
        const _contractAndstationId = `${item?.contractId ?? ''}-${item?.stationId ?? ''}`;
        //去重
        return noRepeat.includes(_contractAndstationId)
          ? false
          : noRepeat.push(_contractAndstationId);
      })
      .map((item) => {
        const _contractAndstationId = `${item?.contractId ?? ''}-${item?.stationId ?? ''}`;

        const _children = item?.childrenContractList
          ? item?.childrenContractList.map((i) => {
              return { ...i, type: IContractType.SUBCONTRACT } as IListType;
            })
          : null;
        return {
          ...item,
          children: _children,
          type: IContractType.MAINCONTRACT,
          contractAndstationId: _contractAndstationId,
          totalContractPrice: parseFloat(item.statisticsPower as string)
            ? item.totalContractPrice
            : 0,
        } as IListType;
      });
  };
  //新疆 字段处理
  const getXJDataSource = (list: IListType[]) => {
    const _list: IListType[] = list?.map((i, k) => {
      i.idx = k.toString();
      if (i.children?.length !== 0) {
        i.father = true;
        // @ts-ignore
        i.children = i.children?.map((m, n) => ({ ...m, idx: k + '_' + n }));
        return i;
      } else {
        return i;
      }
    });
    // const _list: IListType[] = list.map((item, index) => {
    //   return {
    //     ...item,
    //     idx: index,
    //   } as IListType;
    // });
    return _list || [];
  };
  // 重置量价图表
  const onResetChart = () => {
    setMonthChartsData('');
    setDateChartsData('');
    setMonthData('');
    setDateData('');
    setPointNum(IPointerType.NINETY_SIX_POINT);
    setNowChartRecord({});
    setIsShow(true);
  };

  const onSearchXinJiang = async (params: ISearchValue) => {
    const data = await getXinjiangContractList(params);
    setDataSource(getXJDataSource(data?.dataList || []));
    setTotalData(data?.periodOfTimeList || []);
    setSelectedRowKeys([]);
    onResetChart();
    setIsLoading(false);
  };

  // 搜索列表
  const onSearch = async (params: ISearchValue) => {
    params.tradeRoleList = params?.tradeRoleList?.length === 2 ? [] : params.tradeRoleList;
    setDataSource([]);
    setIsError(false);
    const isXJ = params.provinceId === '65';
    setIsXinJiang(isXJ);
    if (isXJ) {
      await onSearchXinJiang(params);
      return;
    }
    const res: any = await postContractList(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const data = getDataSource(res.data || [], params);
      setDataSource(data || []);
      setSelectedRowKeys([]);
      onResetChart();
    } else {
      message.error(res?.message || '系统异常');
      setIsError(true);
    }

    setIsLoading(false);
  };

  //列表请求参数处理
  const getListParams = (values: any) => {
    const { regionId } = values;
    const params: any = {
      beginDate: values?.beginDate,
      endDate: values?.endDate,
      stationIdList: values?.stationIdList,
      contractTypeCodes: values?.contractTypeCodes || [],
      tradeRoleList:
        values?.tradeRoleList && values?.tradeRoleList === ITradeDirectionType.ALL_DIRECTION
          ? [ITradeDirectionType.BUY, ITradeDirectionType.SELL]
          : [values.tradeRoleList],
      contractSourceList:
        values?.contractSourceList && values?.contractSourceList === IContractSourceType.ALL_TYPE
          ? [
              IContractSourceType.TRADING_CENTER,
              IContractSourceType.TRADING_CENTER_NOMAL,
              IContractSourceType.TRADING_CENTER_VIRTUAL,
              IContractSourceType.USER_UPLOAD,
            ]
          : [values.contractSourceList],
      keyWords: values?.keyWords,
      storageCapacityCalcList:
        values?.storageCapacityCalcList &&
        values?.storageCapacityCalcList === IPositionsCalculateType.ALL_TYPE
          ? [IPositionsCalculateType.DROP_OUT, IPositionsCalculateType.TAKE_PART_IN]
          : [values.storageCapacityCalcList],
    };

    // 如果选中的省份为新疆
    if (regionId === '65') {
      // params.userTypeList = values.userTypeList;
      params.provinceId = regionId;
    } else {
      params.provinceIds = [regionId];
    }
    return params;
  };

  // 请求数据参数处理
  const onChange = (values: IFromValue) => {
    setFormValue(values);
    setIsLoading(true);
    const params = getListParams(values);
    onSearch(params);
  };

  // 新增合约
  const addContract = () => {
    const resoult = havePermissions(
      IContractPermissions.CONTRACTMANAGEMENTADDBUTTON,
      buttonPermissions,
    );
    if (resoult) {
      setNowRecord({});
      setDrawerType(IDrawerType.ADD);
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      handleDarwerVisible(true);
    }
  };

  // 根据勾选构建要导出的数组
  const buildExportData = (arr: any[]) => {
    let list: any[] = [];
    const fun = (i: any) => {
      if (i.children?.length) {
        i.children.map((m: any) => {
          if (selectedRowKeys?.includes(m.idx)) {
            if (!list.some((s) => s.stationName === m.stationName)) {
              let obj = {};
              arr.forEach((f) => {
                if (f.stationName === m.stationName && f.father) {
                  obj = { ...f, children: [m] };
                  list.push(obj);
                }
              });
            } else {
              list.forEach((l) => {
                if (l.stationName === m.stationName) {
                  l.children.push(m);
                }
              });
            }
          }
        });
      }
    };
    if (!selectedRowKeys.length) {
      list = arr;
    } else {
      arr.forEach((i) => {
        if (selectedRowKeys?.includes(i.idx) && i.father) {
          if (!list.some((s) => s.stationName === i.stationName && s.father)) {
            list.push({ ...i, children: [] });
            fun(i);
          }
        } else {
          fun(i);
        }
      });
    }
    return list;
  };

  // 设置导出的值
  const setExportValue = (arr: any[]) => {
    const setValueFun = (i: any) => {
      i.userType = USER_TYPE_DIC.filter((v: any) => v.value === i.userType)?.[0]?.label;
      i.contractSource = i.contractSource
        ? contractSourceOptions.find((item) => item.value === i.contractSource)
        : {};
      i.contractSource = i.contractSource?.label || '-';
      i.powerSourceType = i.powerSourceType;
      i.month = i.month ? moment(i.month).format('YYYYMM') : '-';
      return i;
    };
    return _.cloneDeep(arr).map((v: any) => {
      if (v.children?.length) {
        v.children = v.children.map((m: any) => setValueFun(m));
      }
      return setValueFun(v);
    });
  };

  // 导出文件
  const handleExportFiles = () => {
    const resoult = havePermissions(
      IContractPermissions.CONTRACTMANAGEMENTADDBUTTON,
      buttonPermissions,
    );

    if (resoult) {
      if (isXinJiang) {
        let data: any = [];
        data = setExportValue(dataSource);
        data = buildExportData(data);
        // const keys = xinjiangExportDic.map((i) => i.code);
        // data = data
        //   ?.filter((t: any) => !selectedRowKeys.length || selectedRowKeys.includes(t.idx))
        //   .map((i: any) =>
        //     keys.map((k: any) => {
        //       if (k === 'tag') {
        //         return timeSliceObjType[i[k]] + '时段';
        //       } else if (k === 'userType') {
        //         return USER_TYPE_DIC.filter((v: any) => v.value === i[k])?.[0]?.label;
        //       } else if (k === 'contractSource') {
        //         const data = i[k] ? contractSourceOptions.find((item) => item.value === i[k]) : {};
        //         return data?.label || '-';
        //       } else if (k === 'powerSourceType') {
        //         return powerTypeList[i[k] - 1 ?? 0];
        //       } else if (k === 'month') {
        //         return i[k] ? moment(i[k]).format('YYYYMM') : '-';
        //       } else {
        //         return i[k];
        //       }
        //     }),
        //   );
        // const header = xinjiangExportDic.map((i) => i.name);
        // const params = {
        //   header: header,
        //   data: data,
        //   filename: '合约信息',
        // };
        const header = xinjiangExportDic.map((i) => ({ header: i.name, key: i.code }));
        exportGroup(data, header, '合约信息');
        // export_json_to_excel(params);
        return;
      }
      const dataFalt: any[] = [];
      dataSource.forEach((x: IListType) => {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        const _obj = dealExportData(x);
        dataFalt.push(Object.values(_obj));
        (x?.children || []).forEach((y) => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          const _childrenObj = dealExportData(y);
          dataFalt.push(Object.values(_childrenObj));
        });
      });
      const params = {
        header: [
          '交易单元',
          '方向',
          '合约名称',
          '合约类型',
          '关联情况',
          '执行期',
          '合约电量(MWh)',
          '统计电量(MWh)',
          '均价(元/MWh)',
          '仓位计算',
          '来源',
        ],
        data: dataFalt,
        filename: '合约信息',
      };
      export_json_to_excel(params);
    }
  };
  // 处理导出数据
  const dealExportData = (x: IListType) => {
    const _tradeRoleData = x?.tradeRole
      ? tradeDirectionOptions.find((item) => item.value === x?.tradeRole)
      : {};
    const _type =
      x?.childrenContractList &&
      x?.childrenContractList?.length > 0 &&
      x.type === IContractType.MAINCONTRACT
        ? '主合约'
        : x.type === IContractType.SUBCONTRACT
        ? '转让合约'
        : '-';
    const _contractStartDate =
      x?.contractStartDate && x?.contractEndDate
        ? `${moment(x?.contractStartDate).format('YYYYMMDD')}-${moment(x?.contractEndDate).format(
            'YYYYMMDD',
          )}`
        : '-';
    const _totalContractQuantity = ToFixed(x?.totalContractQuantity, 3);
    const _statisticsPower = ToFixed(x?.statisticsPower, 3);
    const _totalContractPrice = ToFixed(x?.totalContractPrice, 3);
    const _storageCapacityCalc = x?.storageCapacityCalc
      ? positionsCalculateOptions.find((item) => item.value === x?.storageCapacityCalc)
      : {};
    const _contractSource = x?.contractSource
      ? contractSourceOptions.find((item) => item.value === x?.contractSource)
      : {};
    return {
      stationName: x?.stationName || '-',
      tradeRole: _tradeRoleData?.label || '-',
      contractName: x?.contractName || '-',
      contractType: x?.contractType || '-',
      content: _type,
      contractStartDate: _contractStartDate,
      totalContractQuantity: _totalContractQuantity,
      statisticsPower: _statisticsPower,
      totalContractPrice: _totalContractPrice,
      storageCapacityCalc: _storageCapacityCalc?.label || '-',
      contractSource: _contractSource?.label || '-',
    };
  };

  // 跳转合约分析
  const gotoContractAnalysis = () => {
    const resoult = havePermissions(
      IContractPermissions.CONTRACTMANAGEMENTANALYSISBUTTON,
      buttonPermissions,
    );
    const selectKey = selectedRowKeys.filter((t) => t !== '-'); //去除合计行
    if (resoult) {
      if (selectKey.length > 0) {
        let contractInfoList: IListType[] = [];
        const _dataSource: IListType[] = extractTree(dataSource, 'children');
        selectKey?.forEach((i) => {
          const obj = _dataSource?.find((item) => {
            return item?.contractAndstationId === i;
          });
          if (obj) {
            contractInfoList.push(obj);
          }
        });
        // @ts-ignore
        contractInfoList = contractInfoList.map((item: IListType) => ({
          contractId:
            item?.type === IContractType.SUBCONTRACT
              ? `${item?.parentContractId}>${item?.contractId}`
              : item?.contractId,
          contractName: item?.contractName,
          stationName: item?.stationName,
          stationId: item?.stationId,
        }));
        OnHistory({
          path: '/ContractAnalysis',
          params: {
            contractInfoList: JSON.stringify(contractInfoList),
            beginDate: formValue.beginDate,
            endDate: formValue.endDate,
          },
          openType: 1,
        });
      } else {
        message.info('请勾选合约后操作');
      }
    }
  };

  // 批量删除
  const onBatchDelete = async () => {
    const resoult = havePermissions(
      IContractPermissions.CONTRACTMANAGEMENTBATCHDELBUTTON,
      buttonPermissions,
    );
    if (resoult) {
      if (selectedRowKeys && selectedRowKeys.length > 0) {
        let haveDeleteData: IListType[] = [];
        const _dataSource: IListType[] = extractTree(dataSource, 'children');
        selectedRowKeys?.forEach((i) => {
          const obj = _dataSource?.find((item) => {
            return item?.contractAndstationId === i;
          });
          if (obj) {
            haveDeleteData.push(obj);
          }
        });
        haveDeleteData = haveDeleteData.filter(
          (item: IListType) => item.contractSource === IContractSourceType.USER_UPLOAD,
        );
        const haveDeleteKeys: any[] = haveDeleteData.map((item) => item.contractId);
        const hintText = `选中合约${selectedRowKeys.length}项，其中可删除合约${haveDeleteKeys.length}项，是否确认删除？`;
        const result: any = await ConfirmModal.show({
          title: '删除合约',
          hintText,
          onOk: async () => {
            const params = {
              contractIdList: haveDeleteKeys,
            };
            if (haveDeleteKeys.length > 0) {
              const res = await postContractDel(params);
              if (res && res.statusCode === HttpCode.SUCCESS) {
                message.info('删除成功！');
              } else {
                message.info(res?.message || '删除失败！');
              }
              return res;
            } else {
              const res = {
                statusCode: 10001, // 不调用接口直接关闭弹框
              };
              return res;
            }
          },
        });
        if (result.index === 1 && result.status === IRequireType?.SUCCES) {
          onChange && onChange(formValue);
        }
      } else {
        message.info('请勾选合约后操作');
      }
    }
  };

  const postContractChartsData = async ({
    contractStartDate,
    contractSource,
    contractId,
    stationId,
  }: IListType) => {
    const params = {
      contractSource,
      contractId,
      stationId,
    };
    const [res1, res2] = await Promise.all([
      postContractDetail(params),
      postCsontractPriceFluctuation(params),
    ]);
    const _nowMonth = contractStartDate
      ? moment(contractStartDate).format('YYYY-MM')
      : moment(new Date()).format('YYYY-MM');
    const _nowDate = contractStartDate
      ? moment(contractStartDate).format('YYYY-MM-DD')
      : moment(new Date()).format('YYYY-MM-DD');
    setNowMonth(_nowMonth);
    setNowDate(_nowDate);
    if (res2 && res2.statusCode === HttpCode.SUCCESS) {
      setMonthData(res2.data);
      setMonthChartsData(res2?.data?.priceFluctuationOfDay[_nowMonth] || '');
    } else {
      message.error(res2.message || '系统异常');
      setIsMonthError(true);
    }
    if (res1 && res1.statusCode === HttpCode.SUCCESS) {
      setDateData(res1.data);
      setDateChartsData(res1?.data?.priceFluctuationOf96[_nowDate] || '');
    } else {
      message.error(res1.message || '系统异常');
      setIsDateError(true);
    }
  };

  // 展示合约量价图表
  const showContratCharts = async (record: IListType) => {
    setIsMonthError(false);
    setIsDateError(false);
    setIsShow(false);
    // 存储当前选择的列表数据
    setNowChartRecord(record);
    // 展开量价分析图组件
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    handelVisible(true);
    setMonthChartsLoading(true);
    setDateChartsLoading(true);
    // 调取获取合约量价数据
    // if (record?.contractName === '合计') {
    //   await postTotalChartsData();
    // } else {
    await postContractChartsData(record);
    // }

    setPointNum(IPointerType.NINETY_SIX_POINT);
    setMonthChartsLoading(false);
    setDateChartsLoading(false);
  };

  // const onChangeHandler = async (point: number, date: any) => {
  //   setDateChartsLoading(true);
  //   const params = getListParams(formValue);
  //   await postOneDay(params, date, point);
  //   setDateChartsLoading(false);
  // };

  // 改变时间
  const onChangeDate = async (date: string, type: IPickerType) => {
    if (type === IPickerType.DATE) {
      setNowDate(date);
      // if (nowChartRecord.contractName === '合计') {
      // onChangeHandler(pointNum, date);
      //   return;
      // }
      if (pointNum === IPointerType.NINETY_SIX_POINT) {
        setDateChartsData(dateData?.priceFluctuationOf96[date] || '');
      } else {
        setDateChartsData(dateData?.priceFluctuationOf24[date] || '');
      }
    } else {
      setNowMonth(date);
      setMonthChartsData(monthData?.priceFluctuationOfDay[date] || '');
    }
  };

  // 24点和96点切换
  const onChangePointNum = async (e: IPointerType) => {
    setPointNum(e);
    // if (nowChartRecord.contractName === '合计') {
    // onChangeHandler(e, nowDate);
    //   return;
    // }
    if (e === IPointerType.NINETY_SIX_POINT) {
      nowDate ? setDateChartsData(dateData?.priceFluctuationOf96[nowDate] || '') : '';
    } else {
      nowDate ? setDateChartsData(dateData?.priceFluctuationOf24[nowDate] || '') : '';
    }
  };

  // 关闭合约量价分析图
  const handelVisible = (e: boolean) => {
    setVisible(e);
    setIsShow(false);
  };

  const xinJiangDelete = async (ids: any) => {
    await ConfirmModal.show({
      title: '删除合约',
      hintText: '是否确认删除本合约？',
      onOk: async () => {
        const res = await deleteXinjiangContract(ids);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          message.info('删除成功！');
          onChange && onChange(formValue);
        } else {
          message.info(res?.message || '删除失败！');
        }
      },
    });
  };

  // 删除列表数据
  const onDetele = async (record: IListType) => {
    if (isXinJiang) {
      await xinJiangDelete([record?.id]);
      return;
    }
    const resoult = havePermissions(
      IContractPermissions.CONTRACTMANAGEMENTDELBUTTON,
      buttonPermissions,
    );
    if (resoult) {
      const result: any = await ConfirmModal.show({
        title: '删除合约',
        hintText: '是否确认删除本合约？',
        onOk: async () => {
          const params = {
            contractIdList: [record?.contractId],
          };
          const res = await postContractDel(params);
          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.info('删除成功！');
          } else {
            message.info(res?.message || '删除失败！');
          }
          return res;
        },
      });
      if (result.index === 1 && result.status === IRequireType?.SUCCES) {
        // 刷新列表接口
        onChange && onChange(formValue);
      }
    }
  };

  // 展示列表详情
  const onDetail = async (record: IListType) => {
    setNowRecord(record);
    setDrawerType(IDrawerType.DETAIL);
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    handleDarwerVisible(true);
  };

  // 编辑列表数据
  const onEdit = async (record: any) => {
    const resoult = havePermissions(
      IContractPermissions.CONTRACTMANAGEMENTEDITBUTTON,
      buttonPermissions,
    );
    if (resoult) {
      setNowRecord(record);
      setDrawerType(IDrawerType.EDIT);
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      handleDarwerVisible(true);
    }
  };

  // 控制抽屉组件的显隐
  const handleDarwerVisible = (e: boolean) => {
    setDrawerVisible(e);
  };

  // 抽屉提交数据事件
  const onSubmit = async (data: any, isDdit = false) => {
    setDrawerLoding(true);
    const res = isXinJiang
      ? isDdit
        ? await postXJContractEdit(data)
        : await postXJContractCreate(data)
      : await postContractEdit(data);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      message.info(drawerType === IDrawerType.ADD ? '新增成功' : '编辑成功');
      onChange(formValue);
    } else {
      message.info(res?.message || (drawerType === IDrawerType.ADD ? '新增失败' : '编辑失败'));
    }
    setDrawerLoding(false);
    return res;
  };

  const getStationData = (arr: any = [], value: any = '') => {
    const stationOptions = arr?.filter((i: any) => i.value === value)[0]?.children || [];
    const stationList = _.flattenDeep(
      stationOptions?.map((a: any) => a?.children?.map((b: any) => b.value)),
    );
    setState({
      stationOptions,
      stationList,
    });
    return { stationOptions, stationList };
  };

  // 初始化获取数据
  const fetchData = async () => {
    setLoading(true);
    const res: any = await getStationLevelThree({ menuCode });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const dealElementResultData = getDealElementOptions(res.data || []);
      const firstItem = dealElementResultData.modalData[0];
      const regionId = firstItem?.value2 ?? '';
      const provinceId = firstItem.value ?? '';
      const { stationOptions, stationList } = getStationData(res.data, res.data[0].value);
      const contractTypeRes = await getContractTypeCodes({ provinceIds: [regionId] });
      if (contractTypeRes?.statusCode === HttpCode.SUCCESS) {
        // @ts-ignore
        const contractTypeCodes = [],
          // @ts-ignore
          contractTypeList = [];
        contractTypeRes?.data?.forEach((d: any) => {
          // @ts-ignore
          if (!contractTypeCodes.includes(d?.contractTypeCode)) {
            contractTypeCodes.push(d?.contractTypeCode);
          }
          contractTypeList.push({
            label: d?.contractTypeName,
            value: d?.contractTypeCode,
          });
        });
        setState({
          power: dealElementResultData?.modalData,
          provinceId,
          // @ts-ignore
          contractTypeList,
        });
        const _fromValue = {
          beginDate: moment().startOf('month').format('YYYY-MM-DD'),
          endDate: moment().endOf('month').format('YYYY-MM-DD'),
          tradeRoleList: ITradeDirectionType.ALL_DIRECTION,
          contractSourceList: IContractSourceType.ALL_TYPE,
          keyWords: '',
          regionId,
          provinceId,
          stationList,
          stationOptions,
          // @ts-ignore
          contractTypeCodes,
          storageCapacityCalcList: IPositionsCalculateType.ALL_TYPE,
          stationIdList: dealElementResultData?.value
            ? dealElementResultData?.value
                ?.filter(
                  (item: IDealElementOptions) =>
                    dealElementResultData?.modalData[0] &&
                    item?.regionId === dealElementResultData?.modalData[0]?.regionId,
                )
                .map((item: IDealElementOptions) => item.value)
            : [],
        };
        setSearchFormData({
          dealElementOptions: dealElementResultData?.value || [],
          dealElementModalOptions: dealElementResultData?.modalData || [],
          dealElementDataObj: dealElementResultData.dataObj,
        });
        // @ts-ignore
        setInitFromValue(_fromValue);
        // @ts-ignore
        onChange(_fromValue);
      }
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <Spin spinning={loading}>
      <div className={styles.container}>
        <div className={styles.header}>
          <Header
            // @ts-ignore
            getStationData={getStationData}
            provinceId={state.provinceId}
            stationOptions={state.stationOptions}
            stationList={state.stationList}
            power={state.power}
            values={formValue}
            searchFormData={searchFormData}
            initialValues={initFromValue}
            contractTypeList={state.contractTypeList}
            addContract={addContract}
            onChange={onChange}
            disabled={!(dataSource?.length > 0) || isLoading || isError}
            handleExportFiles={handleExportFiles}
          />
        </div>
        <div className={styles.main}>
          <div className={styles.content}>
            <div className={styles.left}>
              <div className={styles.leftHeader}>
                <div className={styles.title}>合约信息</div>
                {isLoading || isError || dataSource?.length === 0
                  ? null
                  : !isXinJiang && (
                      <Space size={'middle'}>
                        <Button type="primary" onClick={gotoContractAnalysis}>
                          合约分析
                        </Button>
                        <Button onClick={onBatchDelete}>批量删除</Button>
                      </Space>
                    )}
              </div>
              <div className={styles.leftBottom}>
                {isLoading ? (
                  <Spin spinning={loading ? false : isLoading} className={styles.spin} />
                ) : isError ? (
                  <TRDefault type={'error'} message={'系统异常'} />
                ) : dataSource?.length > 0 ? (
                  //仅在单独选择新疆省时
                  isXinJiang ? (
                    <XJList
                      totalData={totalData}
                      dataSource={dataSource}
                      visible={visible}
                      contractId={nowChartRecord?.contractId}
                      selectedRowKeys={selectedRowKeys}
                      setSelectedRowKeys={setSelectedRowKeys}
                      buttonPermissions={buttonPermissions}
                      showContratCharts={showContratCharts}
                      onDetele={onDetele}
                      onDetail={onDetail}
                      onEdit={onEdit}
                    />
                  ) : (
                    <List
                      dataSource={dataSource}
                      overviewData={overviewData}
                      visible={visible}
                      contractId={nowChartRecord?.contractId}
                      selectedRowKeys={selectedRowKeys}
                      setSelectedRowKeys={setSelectedRowKeys}
                      buttonPermissions={buttonPermissions}
                      showContratCharts={showContratCharts}
                      onDetele={onDetele}
                      onDetail={onDetail}
                      onEdit={onEdit}
                    />
                  )
                ) : (
                  <TRDefault type={'emptysm'} message={'暂无数据'} />
                )}
              </div>
            </div>
            {visible ? (
              <QueueAnim
                interval={[100, 0]}
                duration={[450, 0]}
                type={['right', 'left']}
                className={styles.right}
              >
                <div className={styles.rightHeader}>
                  <div className={styles.title}>
                    {isShow ? null : (
                      <Tooltip placement="topLeft" title={nowChartRecord?.contractName}>
                        {nowChartRecord?.contractName ?? ''}
                      </Tooltip>
                    )}
                  </div>
                  <div onClick={() => handelVisible(false)} className={styles.inVisible}>
                    <CloseOutlined className={styles.logo} />
                  </div>
                </div>
                {isShow ? (
                  <TRDefault type={'emptysm'} message={'请选择合约'} />
                ) : (
                  <div className={styles.content}>
                    <div className={styles.top}>
                      {monthChartsLoading ? (
                        <Spin spinning={monthChartsLoading} />
                      ) : isMonthError ? (
                        <TRDefault type={'emptysm'} message={'系统异常'} />
                      ) : (
                        <div className={styles.monthCharts}>
                          <div className={styles.datePicker}>
                            <SpecialDatePicker
                              value={nowMonth}
                              onChange={onChangeDate}
                              type={IPickerType.MONTH}
                              format="YYYY年MM月"
                              startDate={nowChartRecord?.contractStartDate}
                              endDate={nowChartRecord?.contractEndDate}
                            />
                          </div>
                          {monthChartsData ? (
                            <div className={styles.charts}>
                              <Charts
                                data={monthChartsData}
                                type={IPickerType.MONTH}
                                date={nowMonth}
                                startDate={nowChartRecord?.contractStartDate}
                                endDate={nowChartRecord?.contractEndDate}
                              />
                            </div>
                          ) : (
                            <TRDefault type={'emptysm'} message={'暂无数据'} />
                          )}
                        </div>
                      )}
                    </div>
                    <div className={styles.line}>{''}</div>
                    <div className={styles.bottom}>
                      {dateChartsLoading ? (
                        <Spin spinning={dateChartsLoading} />
                      ) : isDateError ? (
                        <TRDefault type={'emptysm'} message={'系统异常'} />
                      ) : (
                        <div className={styles.dateCharts}>
                          <div className={styles.datePicker}>
                            <SpecialDatePicker
                              value={nowDate}
                              onChange={onChangeDate}
                              type={IPickerType.DATE}
                              format="YYYY年MM月DD日"
                              startDate={nowChartRecord?.contractStartDate}
                              endDate={nowChartRecord?.contractEndDate}
                            />
                            <Pointer
                              value={pointNum}
                              options={pointerOptions}
                              onChange={onChangePointNum}
                            />
                          </div>
                          {dateChartsData ? (
                            <div className={styles.charts}>
                              <Charts
                                data={dateChartsData}
                                type={IPickerType.DATE}
                                date={nowDate}
                                pointNum={pointNum}
                              />
                            </div>
                          ) : (
                            <TRDefault type={'emptysm'} message={'暂无数据'} />
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </QueueAnim>
            ) : null}
          </div>
        </div>
        {isXinJiang ? (
          <XJDetail
            width={'60%'}
            stationOptions={state.stationOptions}
            contractId={nowRecord?.contractId}
            contractSource={nowRecord?.contractSource}
            stationId={nowRecord?.stationId}
            date={nowRecord?.date}
            tag={nowRecord?.tag}
            id={nowRecord?.id}
            visible={drawerVisible}
            searchFormData={searchFormData}
            isLoading={drawerLoading}
            drawerType={drawerType}
            onClose={() => {
              setDrawerLoding(false);
              handleDarwerVisible(false);
            }}
            onSubmit={onSubmit}
          />
        ) : (
          <Detail
            width={'60%'}
            contractId={nowRecord?.contractId}
            contractSource={nowRecord?.contractSource}
            stationId={nowRecord?.stationId}
            visible={drawerVisible}
            searchFormData={searchFormData}
            isLoading={drawerLoading}
            drawerType={drawerType}
            onClose={() => {
              setDrawerLoding(false);
              handleDarwerVisible(false);
            }}
            onSubmit={onSubmit}
          />
        )}
      </div>
    </Spin>
  );
};

export default connect(({ contractManagement, global }: any) => ({
  global,
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
  contractManagement,
}))(ContractManagement);
